package controllers;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import models.Picture;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.codehaus.jackson.node.ObjectNode;

import other.Utils;
import play.data.Form;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Http.MultipartFormData;
import play.mvc.Http.MultipartFormData.FilePart;
import play.mvc.Result;
import play.mvc.Security;

@Security.Authenticated(Secure.class)
public class Pictures extends Controller {

    static Form<Picture> pictureForm;

    public static Result index() {
        return ok(views.html.User.Picture.index.render());
    }

    public static Result listPictures() {
        return ok(views.html.User.Picture.listPictures.render(Picture.find.all(), session().get("keyId"), session()
                .get("vCode")));
    }

    public static Result uploadForm(Long id) {
        pictureForm = Form.form(Picture.class);
        // Fill form with values
        if (id > 0) {
            pictureForm = pictureForm.fill(Picture.find.byId(id));
        }
        return ok(views.html.User.Picture.uploadPicture.render(pictureForm, ""));
    }

    public static Result upload() {
        Form<Picture> filledPictureForm = pictureForm.bindFromRequest();
        MultipartFormData body = request().body().asMultipartFormData();
        FilePart pictureFile = body.getFile("picture");
        String extension = FilenameUtils.getExtension(pictureFile.getFilename());

        // Remove wrong errors
        filledPictureForm.errors().remove("url");
        filledPictureForm.errors().remove("creationDate");
        filledPictureForm.errors().remove("isValid");

        if (filledPictureForm.hasErrors()) {
            // Return error if empty name/description
            return ok(views.html.User.Picture.uploadPicture.render(filledPictureForm, ""));
        } else if (pictureFile.getFilename().isEmpty()) {
            // Return error if no file was selected
            return ok(views.html.User.Picture.uploadPicture.render(filledPictureForm,
                    "<p class='error'>A picture is required</p>"));
        } else if (!extension.matches("jpg|jpeg|png$")) {
            // Return error if picture isn't a jpg/jpeg/png
            return ok(views.html.User.Picture.uploadPicture.render(filledPictureForm,
                    "<p class='error'>A picture in jpg/jpeg/png only !</p>"));
        } else {
            ObjectNode result = Json.newObject();
            result.put("redirect", true);
            Picture picture = (!filledPictureForm.field("id").value().isEmpty()) ? Picture.find.byId(Long
                    .valueOf(filledPictureForm.field("id").value())) : new Picture();
            try {
                picture.setName(filledPictureForm.field("name").value());
                picture.setDescription(filledPictureForm.field("description").value());
                if (picture.getId() == null) {
                    picture.setCreationDate(new Date());
                    picture.setIsValid(true);
                    picture.save();
                    picture.setUrl("assets/pictures/" + picture.getId() + "." + extension);
                    picture.update();
                    FileUtils.copyFile(pictureFile.getFile(), new File(Utils.assetToPhysicalPath(picture.getUrl())));
                } else {
                    FileUtils.copyFile(pictureFile.getFile(), new File(Utils.assetToPhysicalPath(picture.getUrl())));
                    picture.update();
                }

                return ok(result);
            } catch (IOException e) {
                // Exception on copy
                return ok(views.html.User.Picture.uploadPicture.render(filledPictureForm,
                        "<p class='error'>Error during upload !</p>"));
            }
        }
    }
}